<!--Api添加信息-->
<template>
  <scroller class="all bg1" @viewappear="viewappear" @viewdisappear="viewdisappear">
    <div>
      <div class="guide bg2">
        <div class="all">
          <text class="font30 text2">{{T('实盘交易的API需要交易权限')}}</text>
          <text class="font24 text3">{{T('API通过AES加密保密，使用时通过区块链非对称加密传输，使用后立即销毁')}}</text>
        </div>
        <div class="but-guide main1" @click="guideClick">
          <text class="font24 text1">{{T('操作指导')}}</text>
        </div>
      </div>
      
      <div class="content">
        
        <!--  -->
        <div class="cell">
          <div class="height80"></div>
          <text class="font32 text2">IP</text>
          <div class="row acenter height70">
            <template v-if="ipStr">
                <text class="font30 text2 text-line1 all" @click="copyIPClick">{{ipStr}}</text>
                <div class="width20"></div>
                <LImage class="img-copy" :src="Config.img('v2_copy.png')" @click="copyIPClick"></LImage>
            </template>
            <template v-else>
              <text class="font30 text2 text-line1 all">{{T('无IP请先获取')}}</text>
              <div class="width20"></div>
              <div class="but-get main-b1" @click="getIPClick">
                <text class="font28 main-t1">{{T('获取IP')}}</text>
              </div>
            </template>
          </div>
          <div class="line line1"></div>
        </div>
        
        <!-- 秘钥 -->
        <div class="cell" v-for="(item, index) in api.param" v-bind:key="index">
          <div class="height80"></div>
          <text class="font32 text2">{{item.name}}</text>
          <div class="row acenter height70">
            <input class="height70 font30 text2 all" v-model="item.value" type="text">
            <LImage class="img-code" :src="Config.img('v2_saoma.png')" @click="codeClick(item)"></LImage>
          </div>
          <div class="line line1"></div>
        </div>

        <!-- 有效期 -->
        <div class="cell">
          <div class="height80"></div>
          <div class="row acenter" @click="timeClick">
            <text class="font32 text2">{{T('API有效期')}}</text>
            <LImage class="img-wenhao" :src="Config.img('v2_wenhao.png')"></LImage>
          </div>
          <div class="row acenter height70">
            <input class="height70 font30 text2 all" v-model="api.validTime" type="text">
            <div class="width20"></div>
            <text class="font30 text2">{{T('天')}}</text>
          </div>
          <div class="line line1"></div>
        </div>

        <div class="but main-bt1" @click="addClick">
          <text class="font30 text1">{{T('导入')}}</text>
        </div>

        <text class="font30 main-t1">{{T('提示')}}</text>
        <div class="height10"></div>
        <text class="font24 text3">{{T('为了账户资产安全及方便查阅交易数据，建议您重新申请API，不要和其它渠道共用')}}</text>
        <!-- <text class="font24 text3" v-if="api.exchangeName == 'OkexV5'">{{T('OKEx V5服务器IP：159.138.39.31')}}</text> -->
      </div>
    </div>
  </scroller>
</template>

<style src="@/_css/style.css" ></style>
<style scoped>
/************* 操作指导 */
.guide {
  flex-direction: row;
  align-items: center;
  border-radius: 24px;

  padding: 30px;

  margin-top: 20px;
  margin-left: 20px;
  margin-right: 20px;
}
.but-guide{
  justify-content: center;
  align-items: center;
  height: 57px;
  border-radius: 12px;

  padding-left: 20px;
  padding-right: 20px;

  margin-left: 20px;
}

/************* 内容 */
.content {
  padding-left: 40px;
  padding-right: 40px;
  padding-bottom: 80px;
}
.cell {
  margin-left: 10px;
  margin-right: 10px;
}
.line{
  height: 1;
}
.img-wenhao {
  width: 26px;
  height: 26px;
  margin-left: 10px;
}
.img-arrow {
  width: 34px;
  height: 34px;
  margin-left: 20px;
}
.img-code {
  width: 62px;
  height: 62px;
  margin-left: 20px;
}
.but {
  justify-content: center;
  align-items: center;
  height: 80px;
  border-radius: 12px;

  margin-top: 60px;
  margin-bottom: 40px;
}
.but-get {
  justify-content: center;
  align-items: center;
  border-radius: 8px;
  height: 45px;
  padding: 0 10px;
  border-width: 1px;
}
.img-copy {
  width: 32px;
  height: 32px;
}

/************* 间距 */
.height70{ 
  height: 70px;
}
.height80 {
  height: 40px;
}
</style>

<script>

//功能
import jdebug from "@/_js/debug";
import jnavigator from "@/_js/navigator";
import jhttps from "@/_js/https";
import jconfig from "@/_js/config";
import jmodal from "@/_js/modal";
import jtime from "@/_js/time";
import japi from "@/_js/api";


const clipboard = weex.requireModule("clipboard");
const weexFunction = weex.requireModule("WeexFunction");

import I18N from "@/_i18n/i18n";
var T = I18N.t;
weexFunction.setTitle(T("添加API"));

export default {


  data() {
    return {
      T:T,
      Config:jconfig,
      isScan:true, //可以扫码-防止卡顿多次跳转

      exchanges:[], //交易所列表
      api:undefined,
      ipStr:'', //IP
    };
  },

  created() {
    var param = weex.config;
    this.exchanges = param.exchanges;
    this.api = this.initData(param.api);
    weexFunction.setTitle(this.api.exchangeName);

    this.httpQueryUserIpList();
    if (this.api.exchangeName == 'OkexV5') {
      // jmodal.alert(T('OKEx V5服务器IP：159.138.39.31'));
    }
  },



  methods: {

    //完全显示
    viewappear() {
      this.httpQueryUserIpList();
    }, 

    //完全隐藏
    viewdisappear() {
    },
    
    initData(api) {

      api.expireDate = api.exchangeName.toLowerCase() == 'huobi' ? '89' : '999';
      api.validTime = api.expireDate;
      for (let index = 0; index < api.param.length; index++) {
        var item = api.param[index];
        item.value = '';
      }
      return api;
    },

    /********************************** https*/
    //http获取服务器IP
    httpQueryUserIpList() {

      var param = {'exchangeName':this.api.exchangeName};
      jhttps.post("server/queryUserIpList",param,true,(data)=>{

        if(data.status == 200){
          this.ipStr = data.data;
        } else {
          jmodal.toast(data.msg);
        }
      });
    },
    

    //http同步APi
    httpSynchroApi(api, key){

      japi.rsaApi(api, key, (rsa)=>{
        var param = {'apiData':rsa};
        jhttps.postX("assetsV2/synchronizationSingelApi",param,true,(data)=>{

          //测试代码
          // var dataStr = JSON.stringify(data);
          // clipboard.setString(dataStr);
          // if (data.states==200 && !Object.keys(data.data).length) {
          //     jmodal.hideLoad();
          //     jmodal.toast(dataStr);
          //     return;
          // }

          if(data.status == 200){
            data = data.data;
            if (!data.apiId) {
              jmodal.hideLoad();
              jmodal.toast(T('API同步失败'));
              return;
            }

            var assets = data.apiId;
            if (assets.isExpire) {
              jmodal.hideLoad();
              jmodal.toast(T('API无效'));
              return
            }

            this.httpApiAccountId(api, assets, rsa);
          } else {
            jmodal.hideLoad();
            jmodal.toast(data.msg);
          }
        });
      });
    },

    //http获取账户标识
    httpApiAccountId(api, assets, rsa){

      var param = {'apiData':rsa};
      jhttps.postX("assetsV2/getApiAccountId", param,true,(data)=>{
        if(data.status == 200){
          var account = data.data;

          //未录入API：走添加逻辑
          if (account.states == 'NORMAL') {
            this.httpAddApi(api, assets, account);
          }
          
          /*1、已录入API，且有策略执行：询问后走续期逻辑
            2、已录入API，且无策略执行：询问后走续添加逻辑*/
          else if (account.states == 'BIND' || account.states == 'UNBIND') {
            
            var parm = {
                  'message':T("您录入的API与名称为&{1}的API Key来自同一账户，确认录入将更新原有API").replace("&{1}", account.apiName)};
            jmodal.confirm(parm, (bool)=>{
              if (bool == "true") {
                account.states == 'BIND' ? this.renewalApi(api, assets, account) : this.httpAddApi(api, assets, account);
              } else {
                jmodal.hideLoad();
              }
            });
          } else {
            jmodal.hideLoad();
            jmodal.toast(T('获取API标识失败'));
          }
        } else {
          jmodal.hideLoad();
          jmodal.toast(data.msg);
        }
      });
    },
    
    //http添加API
    httpAddApi(api, assets, account) {
      
      var param = {'exchangeId':api.exchangeId,
                  'exchangeName':api.exchangeName,
                  'accountId':account.accountId};
      jhttps.postX("assetsV3/addUserApi",param,true,(data)=>{
        if(data.status == 200){
          var data = data.data;

          //基础数据+API数据+资产数据+账户数据
          var timestamp =  new Date().getTime();
          data.importTime = timestamp; 
          data.synchroTime = timestamp;
          var model = {...data, ...api, ...assets, ...account};
          japi.addApi(model, ()=>{
            jmodal.hideLoad();
            jmodal.toast(T('导入成功'));
            jnavigator.back(2);
          });
        } else {
          jmodal.hideLoad();
          jmodal.toast(data.msg);
        }
      });
    },
    
    //http续期API
    httpRenewalApi(api, assets, account, key) {
      
      japi.rsaApi(api, key, (rsa)=>{
        var param = {'apiId':account.apiId,
                    'apiData':rsa};
        jhttps.postX("assetsV2/apiRenewal",param,true,(data)=>{
          if(data.status == 200){
            
            //API数据+资产数据+账户数据
            var timestamp =  new Date().getTime();
            api.importTime = timestamp; 
            api.synchroTime = timestamp;
            var model = {...api, ...assets, ...account};
            japi.addApi(model, ()=>{
              jmodal.hideLoad();
              jmodal.toast(T('导入成功'));
            jnavigator.back(2);
            });
          } else {
            jmodal.hideLoad();
            jmodal.toast(data.msg);
          }
        });
      });
    },

    /********************************** 其他*/
    //添加API
    addAPI() {
      
      var api = JSON.parse(JSON.stringify(this.api));
      jmodal.showLoad();
      japi.httpPublicKey('api', false, (publicKey)=>{
        this.httpSynchroApi(api, publicKey);
      }, (msg)=>{
        jmodal.hideLoad();
        jmodal.toast(msg);
      });
    },

    //续期API
    renewalApi(api, assets, account) {
      
      japi.httpPublicKey('api', true, (publicKey)=>{
        this.httpRenewalApi(api, assets, account, publicKey);
      }, (msg)=>{
        jmodal.hideLoad();
        jmodal.toast(msg);
      });
    },

    /********************************** 点击触发*/
    //操作指导
    guideClick() {

      var exchangeName = this.api.exchangeName;
      var param = {'exchange':exchangeName}
      var nav = {'navColor':'#0c0c0c'};
      var url =  'apiguides/'+exchangeName.toLowerCase();
      jnavigator.open('', url, param, nav);
    },

    //选择交易所
    exchangeClick() {

      var exchangeNames = [];
      var exchanged = {};
      for (let index = 0; index < this.exchanges.length; index++) {
        var exchange = this.exchanges[index];
        exchangeNames.push(exchange.exchangeName);
        exchanged[exchange.exchangeName] = exchange;
      }
      jmodal.actionSheet(exchangeNames, this.api.exchangeName, (value)=>{
        this.api = this.initData(exchanged[value]);
      });
    },
    
    //扫码点击
    codeClick(item) {

      this.isScan = true;
      setTimeout(() => {
        this.isScan = false;
      }, 1000);

      weexFunction.scanCode((str)=>{
        
        var exchangename = this.api.exchangeName.toLowerCase();
        if (exchangename == 'binance' || exchangename == 'okex' || exchangename == 'okexv5') {
          var api;
          try {
            api = JSON.parse(str);
          } catch (error) {
            item.value = str;
            return;
          }
          for (let index = 0; index < this.api.param.length; index++) {
            var param = this.api.param[index];
            param.value = api[param.field];
          }
        } else {
          item.value = str;
        }
      });
    },

    //有效天数
    timeClick() {
      var parm = {'message':'有效期请在您的交易所账户API管理界面查询。'};
      jmodal.alert(parm,(bool)=>{});
    },

    //导入
    addClick() {

      for (let index = 0; index < this.api.param.length; index++) {
        var param = this.api.param[index];
        if (!param.value) {
            jmodal.toast(T('请输入&{1}').replace('&{1}', param.name));
            return;
        }
        param.value = param.value.trim();
      }

      if (!this.api.validTime) {
        jmodal.toast(T('请输入API有效期'));
        return;
      }


      this.addAPI();
    },

    //获取ip
    getIPClick() {

      var param = {'avatar': ''}; //头像url
      var nav = {'navColor':'#1677fe'};
      jnavigator.open('', "mine/Vip", param, nav);
      // jnavigator.open('', 'server/Server');
    },

    //复制ip
    copyIPClick() {
      jmodal.toast({message:T('复制成功'), duration:2});
      clipboard.setString(this.ipStr);
    }
  },
};

</script>
